package com.relax.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

public class NioTest12_server_atguigu {
    private static Set<SocketChannel> socketChannelHashSet = new HashSet<>();

    public static void main(String[] args) throws IOException {
        /**
         * 服务端四部
         */

        /** 1.创建ServerSocketChannel,并绑定监听端口    */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(6666));

        /** 2.将serverSocket绑定在 selector上   */
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        /**
         * 3.服务区死循环,处理selector对应的事件
         */
        while (true) {
            //1.阻塞等待事件
            if (selector.select(1000) == 0) {
                continue;
            }

            //2.获得所有的SelectionKey
            final Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("服务端监听到事件"+System.nanoTime());
            for (SelectionKey selectionKey : selectionKeys) {
                SocketChannel socketChannel;
                try {
                    /** 3-1.如果是连接事件,把client的socket放在set中用于后面的数据分发 */
                    if (selectionKey.isAcceptable()) {
                        final ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();
                        //获取client的socketchannel--并注册到selector
                        socketChannel = serverSocketChannel1.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        socketChannelHashSet.add(socketChannel);
                    } else if (selectionKey.isReadable()) {
                        /** 3-2.处理clinet发送的消息*/
                        Charset charset = Charset.forName("utf-8");
                        socketChannel = (SocketChannel) selectionKey.channel();
                        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        final int read = socketChannel.read(byteBuffer);
                        if (read > 0) {
                            byteBuffer.flip();
                            String msg = String.valueOf(charset.decode(byteBuffer).array());
                            System.out.println(socketChannel + ",客户端发送的数据为:" + msg);
                            //将客户端发送数据广播出去
                            for (SocketChannel clientChannel : socketChannelHashSet) {
                                final ByteBuffer byteBuffer1 = ByteBuffer.allocate(1024);
                                byteBuffer1.put(("客户端发送的数据为:" + msg).getBytes());
                                byteBuffer1.flip();
                                clientChannel.write(byteBuffer1);
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //清空
            selectionKeys.clear();
        }
    }
}
